﻿using d1Common;
using d1Common.WebController;
using d1Project.Modules.Common.do4A.Domain;
using d1Project.Modules.Common.do4A.Models;
using d1Project.Tools;
using d1Project.Tools.PagedList;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    /// <summary>
    /// 用户3
    /// </summary>
    [Route("do4A/a1/User3")]
    public class User3Controller : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        [PermissionCheck(Id = "do4A$User3", Operation = 0)]
        public async Task<IHttpActionResult> Get([FromUri]User3GetVm model)
        {
            string fileAllPath = doServices.Instance.DoStorage.getAccessUrl("");

            var entities = db.User3s.AsQueryable();

            if (!string.IsNullOrEmpty(model.Code))
            {
                entities = entities.Where(t => t.Code == model.Code);
            }
            if (!string.IsNullOrEmpty(model.Name))
            {
                entities = entities.Where(t => t.Name.Contains(model.Name));
            }
            if (!string.IsNullOrEmpty(model.MobliePhone))
            {
                entities = entities.Where(t => t.MobilePhone == model.MobliePhone);
            }
            int count = await entities.CountAsync();

            var result = await entities.Select(t => new
            {
                t.Id,
                t.Code,
                t.Name,
                Icon = t.Icon,
                IconLong = fileAllPath + t.Icon,
                t.MobilePhone,
                t.Address,
                t.Email,
                t.Sex,
                t.CreateById,
                t.CreateByName,
                t.CreateTime,
                t.UpdateTime,
                t.IsAvailable
            }).OrderByDescending(t => t.CreateTime).ToPagedListAsync(model);

            return Ok(new { rows = result, total = count });
        }

        [PermissionCheck(Id = "do4A$User3", Operation = 0)]
        public async Task<IHttpActionResult> Get(string Id)
        {
            string fileAllPath = doServices.Instance.DoStorage.getAccessUrl("");

            var entity = await db.User3s.Where(t => t.Id == Id)
                .Select(t => new
                {
                    t.Id,
                    t.Code,
                    t.Name,
                    IconLong = fileAllPath + t.Icon,
                    Icon = t.Icon,
                    t.MobilePhone,
                    t.Address,
                    t.Email,
                    t.BirthDay,
                    t.IdCard,
                    t.IsAvailable,
                    t.Sex,
                    t.CreateById,
                    t.CreateByName,
                    t.CreateTime,
                    t.UpdateById,
                    t.UpdateByName,
                    t.UpdateTime
                }).FirstOrDefaultAsync();

            if (entity == null) this.Error("用户不存在");

            return Ok(entity);
        }

        [PermissionCheck(Id = "do4A$User3", Operation = 2)]
        public async Task<IHttpActionResult> Post(User3PostVm model)
        {
            if (!ModelState.IsValid) this.Error("验证不通过");

            if (!string.IsNullOrEmpty(model.Code))
            {
                var old = await db.User3s.Where(x => x.Code == model.Code).FirstOrDefaultAsync();
                if (old != null) this.Error("编码不能重复");
            }
            if (!string.IsNullOrEmpty(model.MobilePhone))
            {
                var old = await db.User3s.Where(x => x.MobilePhone == model.MobilePhone).FirstOrDefaultAsync();
                if (old != null) this.Error("电话不能重复");
            }
            if (!string.IsNullOrEmpty(model.Email))
            {
                var old = await db.User3s.Where(x => x.Email == model.Email).FirstOrDefaultAsync();
                if (old != null) this.Error("邮箱不能重复");
            }

            User3 entity = new User3();
            entity.Id = doServices.Instance.DoCore.getGUID();
            entity.Code = model.Code;
            entity.Name = model.Name;
            entity.Icon = model.Icon;
            entity.BirthDay = model.BirthDay;
            entity.MobilePhone = model.MobilePhone;
            entity.Email = model.Email;
            entity.Sex = model.Sex;
            entity.IdCard = model.IdCard;
            entity.Address = model.Address;
            entity.IsAvailable = model.IsAvailable;
            entity.CreateById = this.UserId;
            entity.CreateByName = this.UserName;
            entity.CreateTime = DateTime.Now;
            entity.UpdateTime = DateTime.Now;
            db.User3s.Add(entity);

            User3Pwd user3pwd = new User3Pwd();
            user3pwd.Id = entity.Id;
            if (string.IsNullOrEmpty(model.Password))
            {
                user3pwd.Password = TextHelper.GetMd5("123456");
            }
            else
            {
                user3pwd.Password = model.Password;
            }

            db.User3Pwds.Add(user3pwd);

            await db.SaveChangesAsync();
            return Ok();
        }

        [PermissionCheck(Id = "do4A$User3", Operation = 4)]
        public async Task<IHttpActionResult> Put(User3PutVm model)
        {
            if (!ModelState.IsValid) this.Error("验证不通过");

            var entity = await db.User3s.FindAsync(model.Id);
            if (entity == null) this.Error("用户不存在");

            if (!string.IsNullOrEmpty(model.Code) && entity.Code != model.Code)
            {
                var old = await db.User3s.Where(x => x.Code == model.Code).FirstOrDefaultAsync();
                if (old != null) this.Error("编码不能重复");
            }
            if (!string.IsNullOrEmpty(model.MobilePhone)&& entity.MobilePhone!=model.MobilePhone)
            {
                var old = await db.User3s.Where(x => x.MobilePhone == model.MobilePhone).FirstOrDefaultAsync();
                if (old != null) this.Error("电话不能重复");
            }
            if (!string.IsNullOrEmpty(model.Email) && entity.Email != model.Email)
            {
                var old = await db.User3s.Where(x => x.Email == model.Email).FirstOrDefaultAsync();
                if (old != null) this.Error("邮箱不能重复");
            }

            entity.Code = model.Code;
            entity.Name = model.Name;
            entity.Icon = model.Icon;
            entity.BirthDay = model.BirthDay;
            entity.MobilePhone = model.MobilePhone;
            entity.Email = model.Email;
            entity.Sex = model.Sex;
            entity.IdCard = model.IdCard;
            entity.Address = model.Address;
            entity.IsAvailable = model.IsAvailable;
            entity.UpdateById = this.UserId;
            entity.UpdateByName = this.UserName;
            entity.UpdateTime = DateTime.Now;
            await db.SaveChangesAsync();
            return Ok();
        }

        [PermissionCheck(Id = "do4A$User3", Operation = 8)]
        public async Task<IHttpActionResult> Delete(string id)
        {
            var entity = await db.User3s.FindAsync(id);
            if (entity == null) this.Error("用户不存在");
            db.User3s.Remove(entity);
            var user3Pwds = db.User3Pwds.Find(id);
            if (user3Pwds != null) db.User3Pwds.Remove(user3Pwds);
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class User3GetVm : VmBase
    {
        /// <summary>
        /// code
        /// </summary>
        public string Code { get; set; }
        /// <summary>
        /// 真实姓名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 手机号
        /// </summary>
        public string MobliePhone { get; set; }
    }

    public class User3PostVm
    {
        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 头像
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 生日
        /// </summary>
        public DateTime? BirthDay { get; set; }

        /// <summary>
        /// 手机
        /// </summary>
        public string MobilePhone { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 性别： 1：男 0：女
        /// </summary>
        public string Sex { get; set; }
        /// <summary>
        /// 身份证号
        /// </summary>
        public string IdCard { get; set; }
        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; }

        /// <summary>
        /// 是否有效 (1：有效，其它无效)
        /// </summary>
        public string IsAvailable { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
    }

    public class User3PutVm
    {
        [Required]
        public string Id { get; set; }

        /// <summary>
        /// 编码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 头像
        /// </summary>
        public string Icon { get; set; }

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 生日
        /// </summary>
        public DateTime? BirthDay { get; set; }

        /// <summary>
        /// 手机
        /// </summary>
        public string MobilePhone { get; set; }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 性别： 1：男 0：女
        /// </summary>
        public string Sex { get; set; }
        /// <summary>
        /// 身份证号
        /// </summary>
        public string IdCard { get; set; }
        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; }

        /// <summary>
        /// 是否有效 (1：有效，其它无效)
        /// </summary>
        public string IsAvailable { get; set; }
    }

}
